require 'libxml'
require 'open-uri'
require File.join(File.dirname(__FILE__), '..', '..', 'lib', 'tools.rb')

class ToolsController < ApplicationController
  before_filter :authorize
 
  def index
    @xml_doc = Shim.new
    
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @shims }
    end
  end
  
  def show 
    case params[:id]
      when "remote_mine": remote_mine
      else redirect_to :action => "index"
    end
  end
  
  def extract_shims
    return(redirect_to :action => "index") if params[:input_file].nil?    
    begin
      file_content = params[:input_file].read
      parse_doc(file_content)
    ensure
      params[:input_file].close!
      return(redirect_to :action => "index")
    end
  end
  
  def remote_mine
    return(redirect_to :action => "index") if params[:file_uri].empty?
    begin
      uri = URI.parse(params[:file_uri])
      file_content = open(uri).read
      uri_to_pass = (uri.to_s.downcase.include?"myexperiment" ? 
          uri.to_s.gsub("/download", "") : uri.to_s)
      parse_doc(file_content, uri_to_pass)
    rescue URI::InvalidURIError
      flash[:notice] = "Please enter a valid URL."
      # LOG ERRORS FROM RESCUE
    ensure
      file_content = nil
      return(redirect_to :action => "index")
    end
  end
  
  protected
  
  def authorize
    unless logged_in? # NOT LOGGED IN
      session[:original_uri] = request.request_uri
      flash[:notice] = "Please log in" 
      redirect_to :controller => "home", :action => "login"
    end
  end
  
  private
  
  def parse_doc(file_content, flow_uri=nil)
    @shims_extracted = 0
    begin   
      model = Tools.get_model(file_content)
      
      # get webservices and beanshells
      processor_collection = model.local_workers
      processor_collection << model.beanshells
      processor_collection.flatten!
      
      # add processors to shims library and store in shims collection
      # the indexes of shim_collection will match those of processor_collection
      # in the event that a shim could not be added to the library, a nil is 
      # entered into the corresponding index position 
      processor_collection.each do |processor| 
        added = Tools.create_objects(current_user, processor, model, flow_uri)
        @shims_extracted+=1 if added
      end
    rescue Exception => ex
#      puts "/* ************************************************************************* */"
#      puts "Exception: #{ex.class.name} - #{ex.message}"
#      puts ex.backtrace
#      puts "/* ************************************************************************* */"   
    ensure
      flash[:notice] = "Shims Extracted - #{@shims_extracted}"
    end
  end
end